package com.example.ticketingserver.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.ticketingserver.dto.R;
import com.example.ticketingserver.entity.Line;
import com.example.ticketingserver.entity.Station;
import com.example.ticketingserver.entity.User;
import com.example.ticketingserver.service.UserService;
import com.example.ticketingserver.utils.QiniuOssUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

import static com.baomidou.mybatisplus.extension.toolkit.Db.getOne;
import static com.baomidou.mybatisplus.extension.toolkit.Db.save;

@CrossOrigin //开启不同源的访问，允许来自任何源的访问。
@Tag(name = "用户接口",description = "用户相关功能接口，包含：登录，添加，修改，删除。")
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @Operation(summary = "用户登录",description = "需要提供用户账号和密码")
    @Parameters({
            @Parameter(name = "username",description = "管理员账号"),
            @Parameter(name = "password",description = "管理员密码")
    })
    @GetMapping("/user/login")
    private R login(User user){
        //获取查询条件构造器
        QueryWrapper<User> query = Wrappers.query(User.class);
        query.eq("username",user.getUsername());
        //执行查询
        User one = getOne(query);
        if(Objects.isNull(one)){
            return R.fail().setMsg("账号不存在");
        }
        if (one.getStatus() !=0){
            return R.fail().setMsg("账号禁用").setCode(1);
        }
//        获取数据库中储存的随即盐组合输入密码加密
        String pwd = SecureUtil.md5(user.getPassword() + one.getSalt());
        user.setPassword(pwd);
        if (Objects.equals(one.getPassword(),user.getPassword())){
            return R.ok().setMsg("登录成功").setData(one);
        }
        return R.fail().setMsg("密码错误！！！").setCode(2);
    }
    @Operation(summary = "用户注册",description = "需要提供用户账号和密码")
    @PostMapping("/user/reg")
    public R add(User user, MultipartFile myfile) throws IOException {
        //获取查询条件构造器
        QueryWrapper<User> query = Wrappers.query(User.class);
        query.eq("username",user.getUsername());
        //执行查询
        User one = getOne(query);
        if(Objects.nonNull(one)){
            return R.fail().setMsg("账号已存在！");
        }
//        生产一个随机盐
        String salt = RandomUtil.randomString(6);
//        将随机盐和用户输入的密码组合加密
        String pwd = SecureUtil.md5(user.getPassword() + salt);
//        将盐和加密后的密码添加到对象中
        user.setSalt(salt);
        user.setPassword(pwd);

        InputStream is = myfile.getInputStream();

        String key = UUID.randomUUID().toString();
        QiniuOssUtils utils = new QiniuOssUtils();
        String path = utils.upload(is, key);

        user.setImg(path);

        //执行添加
        boolean b = userService.save(user);
        if(b){
            return R.ok().setData(user).setMsg("上传成功");
        }
        //失败时从云存储中同时删除文件
        utils.delete(key);
        return R.fail().setMsg("上传失败");
    }
    @Operation(summary = "用户修改",description = "需要提供用户id")
    @PutMapping("/user/update")
    public R modify(@RequestBody User user){
        if (Objects.nonNull(user.getPassword())){
            //        生产一个随机盐
            String salt = RandomUtil.randomString(6);
//        将随机盐和用户输入的密码组合加密
            String pwd = SecureUtil.md5(user.getPassword() + salt);
//        将盐和加密后的密码添加到对象中
            user.setSalt(salt);
            user.setPassword(pwd);
        }
//        根据id修改管理员信息(务必传入管理员id)
        boolean b = userService.updateById(user);
        return b ? R.ok().setMsg("修改成功！").setData(user) : R.fail().setMsg("修改失败！");
    }
    @Operation(summary = "用户删除",description = "需要提供用户id")
    @DeleteMapping("/user/del/{id}")
    public R delById(@PathVariable("id") Integer id){
        User user = userService.getById(id);
        if(Objects.isNull(user)){
            return R.fail().setMsg("该管理员不存在！");
        }
        return userService.removeById(id) ? R.ok().setMsg("删除成功！").setData(user) : R.fail().setMsg("删除失败！");

    }

    /**
     * 分页查询
     * @param page
     * @param limit
     * @return
     */
    @Operation(summary = "用户列表",description = "显示所有用户信息，含分页功能，需要提供当前页码（page），以及每页限制条数（limit）")
    @Parameters({
            @Parameter(name = "page",description = "当前页码",required = true),
            @Parameter(name = "limit",description = "每页的条数",required = true),
    })
    @GetMapping("/user/list")
    public R list(@RequestParam(defaultValue = "1") Integer page,@RequestParam(defaultValue = "5") Integer limit){
//        执行分页查询
        List<User> list = userService.list(new Page<User>(page, limit));
        long count = userService.count();
        return R.ok().setData(list).setCount(count);
    }
    @Operation(summary = "查询所有用户",description = "所有用户")
    @GetMapping("/user/listAll")
    public R queryAll(){
        List<User> list = userService.list();
        return R.ok().setMsg("查询成功").setData(list);
    }
    @Operation(summary = "黑名单列表",description = "显示所有黑名单信息，含分页功能，需要提供当前页码（page），以及每页限制条数（limit）")
    @Parameters({
            @Parameter(name = "page",description = "当前页码",required = true),
            @Parameter(name = "limit",description = "每页的条数",required = true),
    })
    @GetMapping("/user/blacklist")
    public R blacklist(@RequestParam(defaultValue = "1") Integer page,@RequestParam(defaultValue = "5") Integer limit){
//        执行分页查询

        List<User> list = userService.list(new Page<User>(page, limit));
        Integer specificName = 1; // 你想查找的特定值

        List<User> filteredList = new ArrayList<>();
        for (User user : list) {
            if (specificName.equals(user.getStatus())) {
                filteredList.add(user);
            }
        }
        long count = userService.count();
        return R.ok().setData(filteredList).setCount(count);
    }
}
